using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Microsoft.SemanticKernel;
using Microsoft.SemanticKernel.ChatCompletion;
using Microsoft.SemanticKernel.Connectors.OpenAI;
using SqlsugarService.Application.AI.LangChain.Dtos;
using System.ComponentModel;
using System.Text.Json;

namespace SqlsugarService.Application.AI.MES
{
    /// <summary>
    /// MES专用LangChain服务接口
    /// </summary>
    public interface IMESLangChainService
    {
        /// <summary>
        /// 处理MES对话并自动调用工具
        /// </summary>
        /// <param name="message">用户消息</param>
        /// <param name="userId">用户ID</param>
        /// <param name="sessionId">会话ID</param>
        /// <returns>处理结果</returns>
        Task<MESChatResult> ProcessMESChatAsync(string message, string userId, string? sessionId = null);
    }

    /// <summary>
    /// MES专用LangChain服务实现
    /// 集成Semantic Kernel和MES工具，提供智能对话和自动工具调用
    /// </summary>
    public class MESLangChainService : IMESLangChainService
    {
        private readonly IConfiguration _configuration;
        private readonly ILogger<MESLangChainService> _logger;
        private readonly IMESToolService _mesToolService;
        private readonly Kernel _kernel;
        private readonly IChatCompletionService _chatCompletionService;
        private readonly Dictionary<string, ChatHistory> _chatHistories = new();

        public MESLangChainService(
            IConfiguration configuration,
            ILogger<MESLangChainService> logger,
            IMESToolService mesToolService)
        {
            _configuration = configuration ?? throw new ArgumentNullException(nameof(configuration));
            _logger = logger ?? throw new ArgumentNullException(nameof(logger));
            _mesToolService = mesToolService ?? throw new ArgumentNullException(nameof(mesToolService));

            // 初始化Semantic Kernel
            var builder = Kernel.CreateBuilder();

            // 配置AI服务
            var apiKey = _configuration["LangChain:ApiKey"] ?? throw new InvalidOperationException("LangChain:ApiKey 配置缺失");
            var endpoint = _configuration["LangChain:Endpoint"];

            if (!string.IsNullOrEmpty(endpoint) && endpoint.Contains("azure"))
            {
                var deploymentName = _configuration["LangChain:ModelName"] ?? "gpt-3.5-turbo";
                builder.AddAzureOpenAIChatCompletion(deploymentName, endpoint, apiKey);
            }
            else
            {
                builder.AddOpenAIChatCompletion(_configuration["LangChain:ModelName"] ?? "gpt-3.5-turbo", apiKey);
            }

            // 暂时不注册插件，使用简化版本
            // builder.Plugins.AddFromObject(new MESToolPlugin(_mesToolService, _logger));

            _kernel = builder.Build();
            _chatCompletionService = _kernel.GetRequiredService<IChatCompletionService>();
        }

        /// <summary>
        /// 处理MES对话并自动调用工具
        /// </summary>
        public async Task<MESChatResult> ProcessMESChatAsync(string message, string userId, string? sessionId = null)
        {
            try
            {
                _logger.LogInformation("开始处理MES对话，用户: {UserId}, 会话: {SessionId}", userId, sessionId);

                sessionId ??= Guid.NewGuid().ToString();
                var memoryKey = $"{userId}:{sessionId}";

                // 获取或创建聊天历史
                var chatHistory = GetOrCreateChatHistory(memoryKey);

                // 添加用户消息
                chatHistory.AddUserMessage(message);

                // 创建执行设置
                var executionSettings = new OpenAIPromptExecutionSettings
                {
                    Temperature = float.Parse(_configuration["LangChain:Temperature"] ?? "0.7"),
                    ModelId = _configuration["LangChain:ModelName"] ?? "gpt-3.5-turbo"
                };

                // 发送消息并获取回复
                var result = await _chatCompletionService.GetChatMessageContentAsync(chatHistory, executionSettings);

                // 保存AI回复到聊天历史
                chatHistory.AddAssistantMessage(result.Content ?? string.Empty);

                _logger.LogInformation("MES对话处理完成，用户: {UserId}", userId);

                // 检查是否需要工具调用
                var needsToolCall = await AnalyzeMessageForToolCall(message);
                var finalMessage = result.Content ?? "抱歉，我无法处理您的请求。";

                // 如果需要工具调用，执行相应的工具
                if (needsToolCall.NeedsCall)
                {
                    var toolResult = await ExecuteToolAsync(needsToolCall.ToolName, needsToolCall.Parameters);
                    finalMessage = FormatToolResponse(toolResult, message);
                }

                return new MESChatResult
                {
                    Success = true,
                    Message = finalMessage,
                    SessionId = sessionId,
                    HasToolCalls = needsToolCall.NeedsCall
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "处理MES对话失败，用户: {UserId}", userId);
                return new MESChatResult
                {
                    Success = false,
                    Message = "抱歉，系统暂时无法处理您的请求，请稍后重试。",
                    SessionId = sessionId ?? Guid.NewGuid().ToString(),
                    ErrorMessage = ex.Message
                };
            }
        }

        /// <summary>
        /// 获取或创建聊天历史
        /// </summary>
        private ChatHistory GetOrCreateChatHistory(string memoryKey)
        {
            if (!_chatHistories.ContainsKey(memoryKey))
            {
                var chatHistory = new ChatHistory();

                // 添加系统提示词
                var systemPrompt = BuildMESSystemPrompt();
                chatHistory.AddSystemMessage(systemPrompt);

                _chatHistories[memoryKey] = chatHistory;
            }

            return _chatHistories[memoryKey];
        }

        /// <summary>
        /// 分析消息是否需要工具调用
        /// </summary>
        private async Task<ToolCallAnalysis> AnalyzeMessageForToolCall(string message)
        {
            var lowerMessage = message.ToLower();

            // 简单的关键词匹配
            if (lowerMessage.Contains("查询") || lowerMessage.Contains("搜索") || lowerMessage.Contains("获取"))
            {
                if (lowerMessage.Contains("订单") && lowerMessage.Contains("生产"))
                {
                    return new ToolCallAnalysis
                    {
                        NeedsCall = true,
                        ToolName = "QueryProductionOrders",
                        Parameters = ExtractOrderParameters(message)
                    };
                }
                else if (lowerMessage.Contains("库存") || lowerMessage.Contains("物料"))
                {
                    return new ToolCallAnalysis
                    {
                        NeedsCall = true,
                        ToolName = "QueryMaterialInventory",
                        Parameters = ExtractMaterialParameters(message)
                    };
                }
                else if (lowerMessage.Contains("销售") && lowerMessage.Contains("订单"))
                {
                    return new ToolCallAnalysis
                    {
                        NeedsCall = true,
                        ToolName = "QuerySalesOrders",
                        Parameters = ExtractSalesParameters(message)
                    };
                }
                else if (lowerMessage.Contains("bom") || lowerMessage.Contains("物料清单"))
                {
                    return new ToolCallAnalysis
                    {
                        NeedsCall = true,
                        ToolName = "QueryBOMInfo",
                        Parameters = ExtractBOMParameters(message)
                    };
                }
            }
            else if (lowerMessage.Contains("报表") || lowerMessage.Contains("统计"))
            {
                return new ToolCallAnalysis
                {
                    NeedsCall = true,
                    ToolName = "GenerateProductionReport",
                    Parameters = ExtractReportParameters(message)
                };
            }

            return new ToolCallAnalysis { NeedsCall = false };
        }

        /// <summary>
        /// 执行工具调用
        /// </summary>
        private async Task<object> ExecuteToolAsync(string toolName, Dictionary<string, object> parameters)
        {
            try
            {
                return toolName switch
                {
                    "QueryProductionOrders" => await _mesToolService.QueryProductionOrdersAsync(parameters),
                    "QueryMaterialInventory" => await _mesToolService.QueryMaterialInventoryAsync(parameters),
                    "QuerySalesOrders" => await _mesToolService.QuerySalesOrdersAsync(parameters),
                    "QueryBOMInfo" => await _mesToolService.QueryBOMInfoAsync(parameters),
                    "GenerateProductionReport" => await _mesToolService.GenerateProductionReportAsync(parameters),
                    _ => new { error = $"未知的工具: {toolName}" }
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "执行工具 {ToolName} 失败", toolName);
                return new { error = ex.Message };
            }
        }

        /// <summary>
        /// 格式化工具响应
        /// </summary>
        private string FormatToolResponse(object toolResult, string originalMessage)
        {
            var jsonResult = JsonSerializer.Serialize(toolResult, new JsonSerializerOptions { WriteIndented = true });

            return $"根据您的查询\"{originalMessage}\"，我为您找到了以下信息：\n\n{jsonResult}\n\n如需更多详细信息，请告诉我具体需要了解什么。";
        }

        /// <summary>
        /// 提取订单参数
        /// </summary>
        private Dictionary<string, object> ExtractOrderParameters(string message)
        {
            var parameters = new Dictionary<string, object>();

            // 简单的参数提取逻辑
            if (message.Contains("今天") || message.Contains("今日"))
            {
                parameters["startDate"] = DateTime.Today.ToString("yyyy-MM-dd");
                parameters["endDate"] = DateTime.Today.ToString("yyyy-MM-dd");
            }

            return parameters;
        }

        /// <summary>
        /// 提取物料参数
        /// </summary>
        private Dictionary<string, object> ExtractMaterialParameters(string message)
        {
            var parameters = new Dictionary<string, object>();

            // 提取物料编码
            var words = message.Split(' ', '，', ',');
            foreach (var word in words)
            {
                if (word.Length > 2 && (word.StartsWith("A") || word.StartsWith("M") || word.StartsWith("P")))
                {
                    parameters["materialCode"] = word;
                    break;
                }
            }

            return parameters;
        }

        /// <summary>
        /// 提取销售参数
        /// </summary>
        private Dictionary<string, object> ExtractSalesParameters(string message)
        {
            return new Dictionary<string, object>();
        }

        /// <summary>
        /// 提取BOM参数
        /// </summary>
        private Dictionary<string, object> ExtractBOMParameters(string message)
        {
            return new Dictionary<string, object>();
        }

        /// <summary>
        /// 提取报表参数
        /// </summary>
        private Dictionary<string, object> ExtractReportParameters(string message)
        {
            var parameters = new Dictionary<string, object>();

            if (message.Contains("今天") || message.Contains("今日"))
            {
                parameters["reportType"] = "daily";
                parameters["startDate"] = DateTime.Today.ToString("yyyy-MM-dd");
                parameters["endDate"] = DateTime.Today.ToString("yyyy-MM-dd");
            }
            else if (message.Contains("本周"))
            {
                parameters["reportType"] = "weekly";
            }
            else if (message.Contains("本月"))
            {
                parameters["reportType"] = "monthly";
            }

            return parameters;
        }

        /// <summary>
        /// 构建MES系统提示词
        /// </summary>
        private string BuildMESSystemPrompt()
        {
            return @"你是一个专业的MES（制造执行系统）智能助手，专门为制造企业提供生产管理支持。

你的能力范围包括：
1. 生产管理：生产订单查询、生产计划制定、进度跟踪
2. 物料管理：库存查询、物料需求计算、采购建议
3. 质量管理：质检数据分析、不良品处理、质量追溯
4. 设备管理：设备状态监控、维护计划、故障诊断
5. 工艺管理：工艺流程指导、参数优化建议
6. 报表分析：生产效率分析、成本统计、趋势预测

回答时请：
- 使用专业但易懂的语言
- 提供具体的操作步骤和实用建议
- 必要时询问更多细节以提供准确帮助

如果遇到超出能力范围的问题，请诚实说明并建议联系相关专业人员。";
        }
    }

    /// <summary>
    /// 工具调用分析结果
    /// </summary>
    public class ToolCallAnalysis
    {
        /// <summary>
        /// 是否需要调用工具
        /// </summary>
        public bool NeedsCall { get; set; }

        /// <summary>
        /// 工具名称
        /// </summary>
        public string ToolName { get; set; } = string.Empty;

        /// <summary>
        /// 工具参数
        /// </summary>
        public Dictionary<string, object> Parameters { get; set; } = new();
    }

    /// <summary>
    /// MES对话处理结果
    /// </summary>
    public class MESChatResult
    {
        /// <summary>
        /// 处理是否成功
        /// </summary>
        public bool Success { get; set; }

        /// <summary>
        /// 回复消息
        /// </summary>
        public string Message { get; set; } = string.Empty;

        /// <summary>
        /// 会话ID
        /// </summary>
        public string SessionId { get; set; } = string.Empty;

        /// <summary>
        /// 是否包含工具调用
        /// </summary>
        public bool HasToolCalls { get; set; }

        /// <summary>
        /// 错误信息
        /// </summary>
        public string? ErrorMessage { get; set; }
    }
}
